import java.io.*;
import java.net.*;
//import java.awt.*;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.beans.EventHandler;
import java.util.*;


public class ConnectionListener extends Thread {

        Terminal hostTerminal;
        ServerSocket listeningSocket;
       
        public void run() {
                startListening();
        }
       
        public ConnectionListener( Terminal host, int port ) throws IOException {
                hostTerminal = host;
               
                listeningSocket = new ServerSocket( port, 4 );
        }
       
        public void startListening() {
               
                System.out.println("ConnectionListener - listening on port " + listeningSocket.getLocalPort() );


                for ( ;; ) {
                        try {
                                handleNewConnection();
                        } catch (IOException e) {
                                System.out.println("ConnectionListener - Error accpeting new connection");
                                e.printStackTrace();
                        }
                }
               
        }
       
        private void handleNewConnection () throws IOException {
               
                Socket setupSocket = null;
                Socket sessionSocket = null;
                BufferedReader reader = null;
                BufferedWriter writer = null;
               
                String strBuffer = null;
               
                int theirPort = 0;
                int ourPort = 0;
               
                int SID = 0;

                System.out.println("ConnectionListener - waiting for incoming connection");
                setupSocket = listeningSocket.accept();
                       
                System.out.println("ConnectionListener - new incoming connection from "
                                                                + setupSocket.getInetAddress().getHostName()
                                                                +":" + setupSocket.getPort() );

                       
                reader = new BufferedReader(new InputStreamReader(setupSocket.getInputStream()) );
                       
                // TODO make new connection threaded
                // System.out.println("ConnectionListener - startListening: waiting on readline");
                       
                // TODO: setup time out logic here?
                while ( strBuffer == null ) {
                        strBuffer = reader.readLine();
                }
                       
                System.out.println( "ConnectionListner - messge: " + strBuffer);

                StringTokenizer tokens = new StringTokenizer(strBuffer);
                String reply_type_string;

            String[] fieldAndValue = new String[2];

        while ( tokens.hasMoreElements() ) {
                       
                reply_type_string = tokens.nextToken();
                fieldAndValue = reply_type_string.split( "=" );
                       
                if( fieldAndValue[0].compareTo("port") == 0 ) {
                        theirPort = Integer.parseInt(fieldAndValue[1]);
                }
                       
        }
               
                   
                System.out.println("ConnectionListener - connecting to requested port " + theirPort);

            // TODO: maybe this should be another try/catch block
            sessionSocket = new Socket( setupSocket.getInetAddress(), theirPort );
            // setupSocket.close();
                   
                System.out.println( "ConnectionListener - sessionSocket: raddr=" + sessionSocket.getInetAddress().getHostName()
                                +" rport=" + sessionSocket.getPort()
                                + " lport="+ sessionSocket.getLocalPort());
                   
            ourPort = sessionSocket.getLocalPort();
                   
                writer = new BufferedWriter(new OutputStreamWriter(sessionSocket.getOutputStream()) );

            writer.write("OKAY port=" + ourPort);
            writer.newLine();
            writer.flush();
                   
                // System.out.println("ConectionListener - startListening: write( OKAY port=" + ourPort + " )\n");

            SID = ourPort;
                // TODO: add error checking
            hostTerminal.createSession(sessionSocket, SID);

        }
       
        /*
        private Socket createNewSocket (int port) {
                Socket newSock = new Socket();
               
                return newSock;
        }
        */
        /*
        private void newSessionAlert() {
                EventHandler.create( ActionListener.class, hostTerminal, "doActionEvent", "");
        }
        */
}

